import {Component} from 'react'
import {connect} from 'react-redux'
import {Button, View} from '@tarojs/components'
import {register} from "@/api/auth";
import {setStorageSync} from "@/utils/common";
import {taroLogin} from "@/utils/taroUtils";
import './index.scss'

type Props = {
	loading: boolean | undefined;
	openid:string;
	dispatch:any;
	phone:string;
}
class Loading extends Component<Props,any> {
	onGetPhone = (e?: any) => {
		const { openid,dispatch } = this.props;
		dispatch({type:'global_updateState',data:{loading:false}})
		register({
			openid,
			encryptedData: e.detail.encryptedData,
			iv: e.detail.iv,
			code:e.detail.code
		}).then((token:string) => {
			if(token){
				setStorageSync('token', token)
				dispatch({type:'user_updateState',data:{isLogin:true}})
			}
		})
	};

	toLogin=()=>{
		this.props.dispatch({type:'user_updateState',data:{isLogin:true}})
	}

	toRegister=(openid)=>{
		this.props.dispatch({type:'global_updateState',data:{loading:true}})
		this.props.dispatch({type:'user_updateState',data:{openid}})
	}
	onAuth = () => {
		taroLogin(this.toRegister,this.toLogin);
	}

	componentDidMount() {
		const {phone}=this.props;
		if(!phone){
			this.onAuth()
		}
	}

	render() {
		const { loading } = this.props
		return loading ? (
				<View className='loading-mask-box-npsp'>
					<View className='loading-la-dl'>
						<View className='loading-cir-la-content'>
							<View className="loadingWrapper">
								<div className="loadingMsg">需要获取您的手机号码</div>
								<Button
									className="loading-btn"
									onGetPhoneNumber={this.onGetPhone}
									open-type="getPhoneNumber"
								>
									确认
								</Button>
							</View>
						</View>
					</View>
				</View>
		) : null
	}
}

export default connect(({ global,user }) => {
	const { loading } = global
	const {openid,phone}=user
	return {
		phone,
		openid,
		loading
	}
})(Loading)
